package fun.qu_an.minecraft.fabric.fzbbl.mixin;

import fun.qu_an.minecraft.fabric.fzbbl.event.PlayerPlaceEvents;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.util.ActionResult;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;

@Mixin(BlockItem.class)
public abstract class BlockItemMixin {
	@Inject(method = "place(Lnet/minecraft/item/ItemPlacementContext;)Lnet/minecraft/util/ActionResult;",
		locals = LocalCapture.CAPTURE_FAILHARD,
		at = @At(
			value = "INVOKE",
			target = "Lnet/minecraft/item/BlockItem;place(Lnet/minecraft/item/ItemPlacementContext;Lnet/minecraft/block/BlockState;)Z"
		), cancellable = true)
	public void onPlayerPlacing(ItemPlacementContext context, CallbackInfoReturnable<ActionResult> cir, ItemPlacementContext processedContext) {
		if (!PlayerPlaceEvents.PLACING.invoker().onPlayerPlacing(processedContext)) { // 脚手架会使 context != processedContext
			cir.setReturnValue(ActionResult.FAIL);
		}
	}

	@Inject(method = "place(Lnet/minecraft/item/ItemPlacementContext;)Lnet/minecraft/util/ActionResult;",
		locals = LocalCapture.CAPTURE_FAILHARD,
		at = @At(
			value = "INVOKE",
			target = "Lnet/minecraft/util/ActionResult;success(Z)Lnet/minecraft/util/ActionResult;"
		))
	public void onPlayerPlaced(ItemPlacementContext context, CallbackInfoReturnable<ActionResult> cir, ItemPlacementContext processedContext) {
		PlayerPlaceEvents.PLACED.invoker().onPlayerPlaced(processedContext);
	}
}
